let express = require('express');
let crypto = require('crypto');
let router = express.Router();
let filter = require('../../components/filter');
let cache = require('../../components/cache');

router.get('/', function (req, res, next) {
    let user = req.session.user;
    if (req.session !== null && req.session.user != null) {
        res.json({"success": true, "data": {"user": user}});
    }
    else {
        res.json({"success": false});
    }

});

router.post('/', function (req, res, next) {
    let params = req.body;

    if (params.name === undefined || params.name === "") {
        res.json({"success": false, "message": "登录用户名不能为空！"});
        return;
    }

    if (params.password === undefined || params.password === "") {
        res.json({"success": false, "message": "密码不能为空！"});
        return;
    }

    req.app.db.query("select * from user where name = ?", [params.name], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "用户名不存在！"});
            return;
        }

        let user = results[0];

        if (user.password !== crypto.createHash("md5").update(params.password).digest('hex')) {
            req.session.destroy();
            res.clearCookie("user");
            res.clearCookie(global.cookieIndentity);delete req.session;
            res.json({"success": false, "message": "密码错误！"});
            return;
        }

        req.app.db.query("select * from role where id = ?", [user.roleId], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            if (results.length === 0) {
                res.json({"success": false, "message": "用户角色信息错误！"});
                return;
            }

            let role = results[0];


            // req.app.db.query("select id, fatherId, type, name, link, image1 as icon from menu where type > 0 and FIND_IN_SET(id, (?)) order by `order` desc", [role.power], function (err, results) {
            //     if (err) {
            //         res.json({"success": false, "message": global.databaseErr, "detail": err});
            //         return;
            //     }
            //
            //     if (results.length === 0) {
            //         res.json({"success": false, "message": "当前用户没有可操作菜单！"});
            //         return;
            //     }
            //
            //     let menus = makeTree(results, 0);
                req.app.db.query("select text, id, type from dic order by `type`, `order` desc", [], function (err, results, fields) {
                    if (err) {
                        res.json({"success": false, "message": global.databaseErr, "detail": err});
                        return;
                    }

                    let dics = {};
                    for (let i = 0; i < results.length; i++) {
                        if (dics[results[i].type] === undefined) {
                            dics[results[i].type] = []
                        }

                        dics[results[i].type].push(results[i]);
                    }

                    delete user.password;
                    // cache.set(user.id, req.sessionID);
                    req.session.user = user;
                    req.session.role = role;

                    res.cookie("user", JSON.stringify({"id": user.id, "name": user.trueName}));
                    // res.cookie("userId", user.id);
                    // res.cookie("sessionId", req.sessionID);
                    res.json({"success": true, "data": {"user": user, "dics": dics}, "message": "登录成功！"});
                });
            // });
        });
    });
});


function makeTree(data, fatherId) {
    let datas = [];
    for (let i = 0; i < data.length; i ++) {
        if (data[i].fatherId === fatherId) {
            data[i].items = makeTree(data, data[i].id);
            datas.push(data[i]);
        }
    }
    return datas;
}

module.exports = router;